import { defineStore } from 'pinia'
import {getRouters} from "@/api/login.js";
import router from "@/routers/index.js";
let modules = import.meta.glob("../views/**/*.vue")


export const useRouterStore = defineStore('routers', {
    state:()=>{
       return {
           routers: [],
           menus: [],
       }
    },
    actions:{
        addDynamicRoutes() {
            return new Promise(resolve => {
                // 向后端请求路由数据
                getRouters().then(res =>{
                    const rdata = JSON.parse(JSON.stringify(res.data))
                    const sdata= JSON.parse(JSON.stringify(res.data))
                    this.menus = filterVisibleRouter(sdata)
                    this.routers = filterAsyncRouter(rdata)
                    this.routers.forEach(m => router.addRoute('/',m))
                    resolve()
                })
            })
        },
    },
    getters:{

    }
})

function filterAsyncRouter(asyncRouterMap) {
    return asyncRouterMap.filter(route => {
        if (route.component) {
            route.component = modules[`../views${route.component}`]
        }
        if (route.children != null && route.children && route.children.length) {
            route.meta.record = false
            route.children = filterAsyncRouter(route.children)
        } else {
            route.meta.record = true
            delete route['children']
            delete route['redirect']
        }
        return true
    })
}

function filterVisibleRouter(asyncRouterMap) {
    const userInfo = JSON.parse(window.localStorage.getItem('miaomiao-userInfo'))
    return asyncRouterMap.filter(route => {
        if (route.children != null && route.children && route.children.length) {
            route.children = filterVisibleRouter(route.children)
        }
        if(userInfo.userName == 'admin' && route.meta.title == '系统管理') return true
        return route.visible == false
    })
}
